package User;

import Operation.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    //主要实现针对用户名找密码这样的逻辑
    //用户名是唯一的，只能查到结果是1或者是0
    //应该给这行加上unique约束
    public User selectByName(String name){
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            connection= DBUtil.getConnection();
            String sql="select * from user where username= ?";
            statement=connection.prepareStatement (sql);
            statement.setString (1, name);
            resultSet=statement.executeQuery();
            if(resultSet.next()){
                //存在用户名 就返回一个具体的对象
                //需要根据当前user是否是管理员，决定返回一个admin的还是normalUser
                boolean isAdmin=resultSet.getInt ("isAdmin")==1;
                User user=null;
                if(isAdmin){
                    user=new Admin();
                }else {
                    user=new Normal();
                }
                user.setUserId (resultSet.getInt ("userId"));
                user.setUserName (resultSet.getString ("username"));
                user.setPassword (resultSet.getString ("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace ();
        }finally {
            DBUtil.close (connection, statement, resultSet);
        }
        return null;
    }
}
